package com.ideas.impl.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * @Author lijian.wu
 * @Date 2024/2/20 16:03
 * fastjson在反序列化时,怎么解析对象中的继承
 */
public class SubClassDeserialization {

    private A a;

    class A {

        private String a;

        public String getA() {
            return a;
        }

        public void setA(String a) {
            this.a = a;
        }

    }

    class B extends A {

        private String b;

        public String getB() {
            return b;
        }

        public void setB(String b) {
            this.b = b;
        }

    }

    public A getA() {
        return a;
    }

    public void setA(A a) {
        this.a = a;
    }

    public static void main(String[] args) {
        SubClassDeserialization text = new SubClassDeserialization();

        B b = text.new B();
        b.setA("aaaaa");
        b.setB("bbbbb");

        text.setA(b);

        String ttt = JSON.toJSONString(text);
        System.out.println(ttt);
        SubClassDeserialization text2 = JSON.parseObject(ttt, SubClassDeserialization.class);

        System.out.println(JSON.toJSONString(text2));
    // 这里的输出结果分别是:
    // {"a":{"a":"aaaaa","b":"bbbbb"}}
    // {"a":{"a":"aaaaa"}}
    // 在第二次反序列化时候,由于Text对象中A存在继承关系。所以出现信息丢失

        //解决办法：子类转父类，泛型等，可以通过WriteClassName这个feature，这样json里会有@type标注真实的类
        String tttt = JSON.toJSONString(text, new SerializerFeature[]{SerializerFeature.WriteClassName});
        System.out.println(tttt);
        SubClassDeserialization text22 = JSON.parseObject(tttt, SubClassDeserialization.class);
//        如果反序列化还是不生效，试试修改为下面的方式
        JSON.parseObject(tttt,  SubClassDeserialization.class, Feature.SupportAutoType);

        System.out.println(JSON.toJSONString(text22));
  }
}
